package com.yyx.jupiter.service.recommend.rerank;


import com.alibaba.fastjson2.JSONObject;
import com.yyx.jupiter.component.UserExposeBloomFilter;
import com.yyx.jupiter.conf.PropertyConfig;
import com.yyx.jupiter.entity.RecomReq;
import com.yyx.jupiter.entity.RecomVideo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;


@Slf4j
@Service
@RefreshScope
public class ExposeFilterRerank implements Rerankable<RecomVideo> {

    @Resource
    PropertyConfig propertyConfig;

    @Resource
    UserExposeBloomFilter userExposeBloomFilter;

    @Override
    public List<RecomVideo> rerank(List<RecomVideo> recomVideos, RecomReq recomReq) throws Exception {
        long startTime = System.currentTimeMillis();

        // 请求体参数
        String requestId = recomReq.getRequestId();
        String strategy = recomReq.getStrategy();
        String userId = recomReq.getUserId();

        // 配置参数
        JSONObject strategyJson = propertyConfig.getStrategy().getJSONObject(strategy);
        boolean logPrintSwitch = MapUtils.getBooleanValue(strategyJson, "logPrintSwitch", false);


        // 布隆过滤器曝光过滤
        List<RecomVideo> rerankRecomVideos = new ArrayList<>();
        List<String> recomVideoIds = recomVideos.stream().map(RecomVideo::getVideoId).toList();
        List<Boolean> isExposed = userExposeBloomFilter.isBFExists(userId, recomVideoIds);
        for (int i = 0; i < recomVideos.size(); i++) {
            if (!isExposed.get(i)) {
                rerankRecomVideos.add(recomVideos.get(i));
            }
        }

        if (logPrintSwitch) {
            log.info("requestId:{}, expose filter elapsed: {} ms, before expose filter: {}, after expose filter: {}", requestId, (System.currentTimeMillis() - startTime), recomVideos.size(), rerankRecomVideos.size());
        }

        return rerankRecomVideos;
    }

}
